package com.shuyun.xxx.guava.offer;

import org.junit.Test;

/**
 * Created by goodb on 2017/5/21.
 */
public class EnumSingleton {
    private EnumSingleton(){}
    public static EnumSingleton getInstance(){
        return Singleton.INSTANCE.getInstance();
    }

    private enum Singleton{
        INSTANCE;
        private EnumSingleton singleton;
        Singleton(){
            singleton = new EnumSingleton();
        }
        public EnumSingleton getInstance(){
            return singleton;
        }
    }

    public static void main(String[] args) {
        EnumSingleton obj1 = EnumSingleton.getInstance();
        EnumSingleton obj2 = EnumSingleton.getInstance();
        System.out.println(obj1 == obj2);
        DoubleCheckSingleton obj3 = DoubleCheckSingleton.getInstance();
        DoubleCheckSingleton obj4 = DoubleCheckSingleton.getInstance();
        System.out.println(obj3 == obj4);
    }

    private static class DoubleCheckSingleton{
        private DoubleCheckSingleton(){}
        private static DoubleCheckSingleton instance;
        public static DoubleCheckSingleton getInstance(){
            if(null == instance){
                synchronized (DoubleCheckSingleton.class){
                    if(null == instance){
                        instance = new DoubleCheckSingleton();
                    }
                }
            }
            return instance;
        }
    }
}
